package com.eralink.unionuhfreader.http;

import android.text.TextUtils;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.eralink.unionuhfreader.util.ToastUtil;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;

import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import okhttp3.ResponseBody;

public class JsonCallBack<T> extends AbsCallback<T> {

    private Type type;
    private Class<T> clazz;

    public JsonCallBack() {
    }

    public JsonCallBack(Type type) {
        this.type = type;
    }

    public JsonCallBack(Class<T> clazz) {
        this.clazz = clazz;
    }

    public void onError(Response<T> response) {
//        Log.d(">>>>>>>>>>>>>>>>>>",response.body().toString());
        System.out.println(response);
        String url ="";
        if (response.getRawResponse()!=null&&response.getRawResponse().request()!=null&&response.getRawResponse().request().url()!=null) {
            url=   response.getRawResponse().request().url().encodedPath();
        }
        if (response.code() == 203) {
            ToastUtil.showToast("登录信息失效,请重新登录");
        } else if (response.code() == 413) {
            ToastUtil.showToast("权限不足,请联系管理员");
        } else if (response.code() == 400) {
            String ss = (String) response.body();
            if (ss != null && TextUtils.isEmpty(ss)) {
                try {
                    JSONObject result = JSON.parseObject(ss);
                    if (result != null && result.getString("code") != null && result.getString("code").equals("040003")) {
                        ToastUtil.showToast("账号或者密码不正确");
                    } else if (result != null && result.getString("mesg") != null) {
                        ToastUtil.showToast(result.getString("mesg"));
                    } else {
                        //  ToastUtils.showToast("result.getString("mesg")");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        } else if (response.code() == 401) {
            Log.d(">>>1212>>>>",response.code()+"");
            ToastUtil.showToast("您暂无权限" + "(" + url + ")");
        } else if (response.code() == 503) {
            Log.d(">>>1212>>>>",response.code()+"");
            ToastUtil.showToast("服务暂停,请稍后再试");
        } else if (response.code() == 500) {
            Log.d(">>>1212>>>>",response.code()+"");
            ToastUtil.showToast("服务错误,请联系管理员"+url);
        } else {
            ToastUtil.showToast("网络错误,请检查网络连接"+url);
        }


    }

    @Override
    public void onSuccess(Response<T> response) {
//        Log.d(">>>>>>", response.body().toString());
    }

    @Override
    public T convertResponse(okhttp3.Response response) throws Throwable {
        if (type == null) {
            if (clazz == null) {
                Type genType = getClass().getGenericSuperclass();
                type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            }
        }
  /*      ResponseBody body = response.body();
        if (body == null) return null;
        String bodyinfo=inputStream2String(body.byteStream());
        body.close();
        T data = null;
        Gson gson = new Gson();
        JsonReader jsonReader = new JsonReader(body.charStream());
        if (type != null) {
            data = gson.fromJson(jsonReader, type);
        } else if (clazz != null) {
            data = gson.fromJson(jsonReader, clazz);
        } else {
            Type genType = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            data = gson.fromJson(jsonReader, type);
        }
        return data;*/


        ResponseBody body = response.body();
        if (body == null) return null;
        Reader aa = body.charStream();
        String bodyInfo = "";
        if (response.isSuccessful()) {

            //防止OOM
            try {
                bodyInfo = inputStream2String(body.byteStream());
                body.close();
                response.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            Log.d(">>ykj", "返回的字段=" + bodyInfo + " 接口地址=" + response.request().url());
        } else {
            int code = response.code();
            if (code == 400) {
                ToastUtil.showToast("登录失败,密码错误");
            } else if (code == 203) {
                ToastUtil.showToast("登录过期,请重新登录");
                throw new Exception("登录过期,请重新登录");
            }
            throw new Exception();
        }

        T data = JSON.parseObject(bodyInfo,type);
       /* Gson gson = new Gson();

        JsonReader jsonReader = new JsonReader(aa);
        if (type != null) {
            data =gson.fromJson(jsonReader,type);//  JSON.parseObject(bodyInfo, type);
        } else if (clazz != null) {
            data =gson.fromJson(jsonReader,clazz);// JSON.parseObject(bodyInfo, clazz);//
        } else {
            Type genType = getClass().getGenericSuperclass();
            Type type = ((ParameterizedType) genType).getActualTypeArguments()[0];
            data = gson.fromJson(String.valueOf(jsonReader), type);
        }*/
        return data;
    }

    public String inputStream2String(InputStream in) throws IOException {
        StringBuffer out = new StringBuffer();
        byte[] b = new byte[4096];
        for (int n; (n = in.read(b)) != -1; ) {
            out.append(new String(b, 0, n));
        }
        return out.toString();
    }
}
